<template>
  <div>
    <div class="styleAddOrEditBox">
      <breadcrumb :titleArr="titleArr" @back="breadcrumbBack" class="bread-crumb"></breadcrumb>
      <div class="search">
        <span>样式名称：</span>
        <el-input class="searchSelect" v-model.trim="styleName" placeholder="请输入样式名称" size="mini"></el-input>
        <span>渠道类型：</span>
        <m7Select class="searchSelect"
          filterable
          v-model="accessType"
          size="mini" :options="accessTypeOpt"
          @change="accessChange"
          :defaultProps="{value: 'value', label: 'label'}"
          placeholder="请选择">
        </m7Select>
        <span>样式模板：</span>
          <m7Select class="searchSelect"
            filterable
            v-model="styleTemp"
            size="mini" :options="styleTempOpt"
            :defaultProps="{value: 'value', label: 'label'}"
            placeholder="请选择">
          </m7Select>
        <span>渠道样式：</span>
        <m7Select class="searchSelect"
          filterable
          v-model="accessStyle"
          size="mini" :options="accessStyleOpt"
          :defaultProps="{value: 'value', label: 'label'}"
          placeholder="请选择">
        </m7Select>
      </div>
      <div class="content">
        <sessionWindowBox
          ref="sessionWindowRef"
          v-show="accessStyle === 'sessionWindow'"
          :isShowSaveAs="!styleId ? false : true"
          :styleTemp="styleTemp"
          @saveFun="saveFun">
        </sessionWindowBox>
        <consultBtn
          ref="consultBtnRef"
          v-show="accessStyle === 'consultBtn'"
          :isShowSaveAs="!styleId ? false : true"
          @saveFun="saveFun">
        </consultBtn>
        <invitationWindow
          ref="invitationRef"
          v-show="accessStyle === 'invitation'"
          :isShowSaveAs="!styleId ? false : true"
          @saveFun="saveFun">
        </invitationWindow>
      </div>
    </div>
    <!-- 另存为窗口 -->
    <el-dialog
      :modal-append-to-body="false"
      lock-scroll
      title="另存为新样式"
      :visible.sync="isShowSaveAs"
      width="30%">
      <span>
        <el-form
          class="m7-form"
          size="mini" :model="saveAsForm" label-position="top" :rules="saveAsFormRule">
          <el-form-item label="样式名称" prop="saveAsName">
            <el-input v-model.trim="saveAsForm.saveAsName" placeholder="请输入样式名称" size="mini"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveAsChannel">取 消</el-button>
        <el-button type="primary" @click="saveAsSureFun">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang='ts'>
import { Component, Vue, Prop, Ref } from 'vue-property-decorator'
import breadcrumb from '@/components/breadcrumb/breadcrumb.vue'
import sessionWindowBox from '@/views/config/webchat/channel/pcAndWap/sessionWindow.vue'
import consultBtn from '@/views/config/webchat/channel/pcAndWap/consultBtn.vue'
import invitationWindow from '@/views/config/webchat/channel/pcAndWap/invitationWindow.vue'
import { channelConfigMoudle } from '@/store/modules/config/channel/index'
import { deepClone } from '@/utils/common'
// eslint-disable-next-line no-unused-vars
import { Form as ElForm } from 'element-ui'
interface BaseInfo {
  name: string,
  type: string,
  _id: string,
  styleType?: string
}
@Component({
  name: 'styleAddOrEdit',
  components: { breadcrumb, sessionWindowBox, consultBtn, invitationWindow }
})
export default class StyleAddOrEdit extends Vue {
  @Ref() private readonly sessionWindowRef !: sessionWindowBox
  @Ref() private readonly consultBtnRef !: consultBtn
  @Ref() private readonly invitationRef !: invitationWindow
  @Prop({ default: [] }) private titleArr!: any
  private $bus: any
  private $message: any

  private saveAsForm = { // 样式名称
    saveAsName: ''
  }

  private saveAsFormRule = {
    saveAsName: [{ required: true, trigger: 'blur', message: '样式名称必填' }]
  }

  private isShowSaveAs = false // 是否展示另存为

  private accessType = 'pc' // 接入类型

  private styleTemp: any = 'system' // 样式模板

  private accessStyle = 'sessionWindow' // 渠道样式下拉

  private styleName = '' // 样式名

  private styleId = '' // 样式id

  private accessTypeOpt = [ // 接入类型下拉数据
    { label: '网站', value: 'pc' },
    { label: 'Wap/H5', value: 'wap' }
  ]

  private styleTempOpt = [
    { label: '默认模板', value: 'system' },
    { label: '广告型模板', value: 'advert' }
  ]

  private accessStyleOpt = [ // 渠道样式下拉数据
    { label: '会话窗口', value: 'sessionWindow' },
    { label: '咨询按钮', value: 'consultBtn' },
    { label: '会话邀请', value: 'invitation' }
  ]

  private breadcrumbBack () { // 面包屑返回
    this.$emit('pageBack')
  }

  private accessChange () {
    this.styleTempOpt = this.accessType === 'pc' ? [
      { label: '默认模板', value: 'system' },
      { label: '广告型模板', value: 'advert' }
    ] : [
      { label: '默认模板', value: 'system' }
    ]
    this.accessStyleOpt = this.accessType === 'pc' ? [
      { label: '会话窗口', value: 'sessionWindow' },
      { label: '咨询按钮', value: 'consultBtn' },
      { label: '会话邀请', value: 'invitation' }
    ] : [
      { label: '会话窗口', value: 'sessionWindow' },
      { label: '咨询按钮', value: 'consultBtn' }
    ]
    this.styleTemp = this.accessType === 'wap' ? 'system' : this.styleTemp
    this.accessStyle = this.accessType === 'wap' ? 'sessionWindow' : this.accessStyle
  }

  private saveFun () { // 保存事件
    this.$nextTick(() => {
      const formRef = this.sessionWindowRef.$refs.sessionWindowForm as ElForm
      const sessionWindow = deepClone(this.sessionWindowRef.sessionWindowForm) // 会话窗口数据
      const consultButton = deepClone(this.consultBtnRef.cnsultBtnForm) // 咨询按钮数据
      const inviteBoxStyle = deepClone(this.invitationRef.invitationForm) // 会话邀请
      if (!this.styleName) {
        this.$message.error('请输入样式名称')
        return
      }
      if (!sessionWindow.companyName) {
        this.$message.error('请输入企业简称')
        return
      }
      formRef.validate(valide => {
        if (valide) {
          let sendUrl = '/im-web/action/config/csstmp/save'
          // {name: 样式名称，type: 接入渠道， sessionWindow: 会话窗口数据，consultButton: 咨询按钮数据， invitation: 会话邀请数据}
          const sendData: any = {
            name: this.styleName,
            type: this.accessType,
            sessionWindow,
            consultButton,
            inviteBoxStyle,
            styleType: this.styleTemp
          }
          let successMsg = '添加样式成功'
          if (this.styleId) { // 编辑操作
            sendUrl = '/im-web/action/config/csstmp/update'
            successMsg = '编辑样式成功'
            sendData._id = this.styleId
          }
          if (this.isShowSaveAs) { // 另存为操作
            if (!this.saveAsForm.saveAsName) {
              this.$message.error('请输入样式名称')
              return false
            }
            delete sendData._id // 另存为时不传_id
            sendData.name = this.saveAsForm.saveAsName
            sendUrl = '/im-web/action/config/csstmp/save'
            successMsg = '添加样式成功'
          }
          const actionData = { url: sendUrl, method: 'POST', data: sendData }
          channelConfigMoudle.channelCommonAction(actionData).then(res => {
            if (res) {
              this.$message.success(successMsg)
              this.isShowSaveAs = false
              if (!sendData._id) {
                (this as any).$addOneCache('cssList', res.data, true) // 更新样式缓存
              } else {
                (this as any).$updateCache('cssList', res.data, '_id', true) // 更新样式缓存
              }
              this.$emit('saveFun', sendData)
            }
          })
        }
      })
    })
  }

  private setBaseInfo (data?: BaseInfo) { // 赋值基本信息事件
    if (data) {
      const { name, type, _id, styleType } = data
      this.styleName = name
      this.accessType = type
      this.styleId = _id
      this.styleTemp = styleType || 'system'
    } else {
      this.styleName = ''
      this.styleTemp = 'system'
      this.accessType = 'pc'
      this.styleId = ''
    }
  }

  private saveAsFun () { // 另存为弹窗事件
    this.isShowSaveAs = true
  }

  private saveAsSureFun () { // 另存为保存事件
    this.saveFun()
  }

  private saveAsChannel () { // 另存为取消事件
    this.saveAsForm.saveAsName = ''
    this.$bus.$emit('styleEdit')
    this.$bus.$emit('styleEditSessionWindow')
    this.$bus.$emit('styleEditConsultBtn')
    this.$bus.$emit('styleEditInvitation')
    this.isShowSaveAs = false
  }

  private mounted () {
    this.$bus.$on('styleEdit', (res: BaseInfo) => {
      if (res) {
        this.setBaseInfo(res)
      } else {
        this.setBaseInfo()
      }
    })
    this.$bus.$on('saveAsFun', () => {
      this.saveAsFun()
    })
  }

  private beforeDestroy () {
    this.$bus.off('saveAsFun')
    this.$bus.off('styleEdit')
  }
}
</script>
<style lang="stylus" scoped>
  .styleAddOrEditBox
    border 1px solid $border-main
    border-radius 10px
    height 100%
    overflow auto
    box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
    box-sizing border-box
    margin 0 2px 2px 0
    background-image -webkit-radial-gradient(#E0E6F0 2px, rgba(0, 0, 0, 0) 2px)
    background-image radial-gradient(#E0E6F0 2px, rgba(0, 0, 0, 0) 2px)
    background-size 20px 20px
    .search
      padding 24px
    .searchSelect
      margin 0px 23px 0px 10px
      display inline-block
      width 150px
    .content
      padding 0 24px 24px
      height calc(100% - 136px)
</style>
